import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import LoginView from '../views/LoginView.vue'
import RegisterView from '../views/RegisterView.vue'
import BusinessDetailView from '../views/BusinessDetailView.vue'
import OrderConfirmView from '../views/OrderConfirmView.vue'
import BusinessListView from '../views/BusinessListView.vue'
import UserView from '../views/UserView.vue'
import AddressView from '../views/AddressView.vue'
import AddressEditView from '../views/AddressEditView.vue'
import OrderView from '../views/OrderView.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      redirect: '/home'
    },
    {
      path: '/home',
      name: 'home',
      component: HomeView
    },
    {
      path: '/login',
      name: 'login',
      component: LoginView
    },
    {
      path: '/register',
      name: 'register',
      component: RegisterView
    },
    {
      path: '/business-list',
      name: 'business-list',
      component: BusinessListView
    },
    {
      path: '/business-detail',
      name: 'business-detail',
      component: BusinessDetailView
    },
    {
      path: '/order-confirm',
      name: 'order-confirm',
      component: OrderConfirmView
    },
    {
      path: '/user',
      name: 'user',
      component: UserView
    },
    {
      path: '/address',
      name: 'address',
      component: AddressView
    },
    {
      path: '/address/edit',
      name: 'address-edit',
      component: AddressEditView
    },
    {
      path: '/order',
      name: 'order',
      component: OrderView,
      meta: {
        requireAuth: true
      }
    }
  ]
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  const publicPages = ['/login', '/register', '/home', '/business-list', '/business-detail']
  const authRequired = !publicPages.includes(to.path)

  if (authRequired && !token) {
    next('/login')
  } else {
    next()
  }
})

export default router 